#ifndef MESSENGER_H
#define MESSENGER_H

#include <QObject>
#include <QAbstractSocket>

#include "message.h"
#include <QTemporaryFile>


class QTcpSocket;
class QProgressDialog;

class Messenger : public QObject
{
    Q_OBJECT
public:
    enum MessengerState {
        NoTask = 0,
        SendData,
        ReceiveData,
        Canceled
    };

    enum MessengerError {
        NoError = 0,
        NoConnection,
        ConnectionLost,
        TransmissionCanceled
    };

    Messenger(const QString& host = QString(), int port = 11000, QProgressDialog *progress = 0);
    ~Messenger();

    MessengerError sendMessage(Message *message);
    MessengerError sendMessage(Message *message, const QString &host, int port, QProgressDialog *progress = 0);
    Message *lastMessage() { return m_lastMessage; }
    void setProgressDialog(QProgressDialog *dialog) { m_progress = dialog; }

public slots:
    void cancel();

private slots:
    void readyRead();
    void socketError( QAbstractSocket::SocketError socketError );

private:
    QString m_remoteHost;
    int m_remotePort;
    QTcpSocket *m_socket;
    QByteArray readBuffer;
    QByteArray m_prevChunkEnd;
    QByteArray m_messageEndBuff;
    Message *m_lastMessage;

    int m_readSize;
    int m_totalSize;

    QTemporaryFile *m_tmpFile;
    MessengerError m_res;
    QProgressDialog *m_progress;
};

#endif // MESSENGER_H
